﻿using DongFangGuoKai.WCSPlatform.WebApi.Controllers;
using DongFangGuoKai.WCSPlatform.WebApi.ExternalSystem.WMSConmmon;
using DongFangGuoKai.WCSPlatform.WebApi.Utils;
using DongFangGuoKai.WMSPlatform.Commn.ExtendModule;
using S7.Net;
using System.Security.Permissions;
using System.Threading;

namespace DongFangGuoKai.WCSPlatform.WebApi.HostService
{
    /// <summary>
    /// 出库后台分拨任务
    /// </summary>
    public class OutWhouseHostService : BackgroundService
    {
        private readonly Plc plc;
        private readonly PlcTaskManager plcTaskManager;
        private readonly ILogger<OutWhouseHostService> logger;
        private readonly IServiceProvider serviceProvider;


        HostOption options = new HostOption();
        /// <summary>
        /// 构造
        /// </summary>
        /// <param name="plc"></param>
        /// <param name="plcTaskManager"></param>
        /// <param name="logger"></param>
        /// <param name="options"></param>
        /// <param name="serviceProvider"></param>
        public OutWhouseHostService
        (
            Plc plc,
            PlcTaskManager plcTaskManager,
            ILogger<OutWhouseHostService> logger,
            Action<HostOption> options, 
            IServiceProvider serviceProvider
        )
        {
            this.plc = plc;
            this.plcTaskManager = plcTaskManager;
            this.logger = logger;
            this.serviceProvider = serviceProvider;
            options.Invoke(this.options);
        }

  
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            // 延迟启动
            await Task.Delay(this.options.CheckTime, stoppingToken);
            try
            {

                logger.LogInformation("出库任务启动");
                while (!stoppingToken.IsCancellationRequested)
                {
                    try
                    {
                        if (plc.IsConnected)
                            plcTaskManager.OutDoWork();
                    }
                    catch (Exception ex)
                    {
                        logger.LogError("出库分拨窗口任务异常:" + ex.Message,ex);
                    }
                    await Task.Delay(1000, stoppingToken);
                }
            }
            catch (Exception ex)
            {
                logger.LogError($"出库分拨窗口任务异常：{ex.Message}",ex);
            }
        }
        public override Task StopAsync(CancellationToken cancellationToken)
        {
            logger.LogInformation("出库后台任务异常结束");
            Dispose();
            return base.StopAsync(cancellationToken);
        }
    }
}
